﻿using Logger4Net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Utilities;

namespace Hubberly
{
   static class Program
   {
      ////////////////////////////////////////////////////////////////////////
      //
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         try
         {
            settings = Archive.create<Config.Hubberly>(Config.Hubberly.CONFIG_SECTION);

            Main mainForm = new Main();
            Application.Run(mainForm);
            settings.save();

            // For developers:
            // We keep a copy so that we can copy it back to App.config if necessary
            string copyName;
            if (!string.IsNullOrWhiteSpace(copyName = Environment.ExpandEnvironmentVariables("%HUBBERLY_COPYCONFIG%")))
            {
               if (File.Exists(copyName))
               {
                  File.Delete(copyName);
               }
               File.Copy(settings.CurrentConfiguration.FilePath, copyName);
            }
         }
         catch (System.Exception ex)
         {
            MessageBox.Show(logger_.exception(ex), "Hubberly");
         }
      }


      //////////////////////////////////////////////////////////////////////////
      //
      public delegate string combineGetValue(Entities.City city);

      public static string combine(out bool allSame, List<Entities.City> cities, combineGetValue getValue)
      {
         string result = string.Empty;
         try
         {
            allSame = cities.All(city =>
            {
               string thisValue = getValue(city);
               if (0 == result.Length)
               {
                  result = thisValue;
               }
               else if (result != thisValue)
               {
                  // Some values are different from others, so we display nothing
                  // and break the iteration
                  result = string.Empty;
                  return false;
               }
               return true;
            });
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
            result = string.Empty;
            allSame = false;
         }
         return result;
      }

      ////////////////////////////////////////////////////////////////////////
      //
      private static Logger logger_ = new Logger(typeof(Program));
      internal static Config.Hubberly settings;
   }
}
